/**
 * Filter
 * Censors bad words.
 *
 * Cassie Chin, Stephen Smetana, Logan Widick
 * CSCE 3530 Program 2
 */

#include <string.h>
#include <stdlib.h> 
#include "filter.h"

typedef struct Word {
  char *uncensored;
  char *censored;
  struct Word *next;
} Word;

typedef struct Filter {
  Word *head;
  int size;
} Filter;

/**
 * Generates a censored word given an uncensored word.
 */
char *getCensored (char *uncensored) {
  int i;
  char *censored = (char *) calloc (strlen(censored)+1, sizeof(char));
  
  for (i=0; i<strlen(uncensored); i++) {
    censored[i] = '*';
  }
  
  return censored;
}

Word *new_Word (char *uncensored) {
  Word *new = (Word *) calloc (1, sizeof(Word));
  new->uncensored = (char *) calloc (20, sizeof(char));
  new->censored = (char *) calloc (20, sizeof(char));

  strcpy(new->uncensored, uncensored);
  strcpy(new->censored, getCensored(uncensored));
  return new;
}

/**
 * Inserts a word into the filter
 */
void Filter_insert (Filter *filter, char *uncensored) {
  Word *new = new_Word (uncensored);

  if (!filter->head) {
    filter->head = new;
    filter->size++;
  }
  else {
    Word *ptr;
    for (ptr = filter->head; ptr; ptr = ptr->next) {
      if (ptr->next == NULL) {
	ptr->next = new;
	filter->size++;
	return;
      }
      else if (strcmp (uncensored, ptr->next->uncensored) < 0) {
	new->next = ptr->next;
	ptr->next = new;
	filter->size++;
	break;
      }
    }
  }
}

void Filter_runFilter (Filter *filter, FILE *f_in, FILE *f_out) {
  char *buffer = (char *) calloc (1024 * sizeof (char));

}

Filter *new_Filter(FILE *fp) {
  Filter *filter = (Filter *) calloc (1, sizeof(Filter));
  
  if (!filter) return;
  if (!fp) return;
  
  int SIZE = 256;
  char *buffer = (char *) calloc (SIZE, sizeof (char));
  
  while (fgets (buffer, SIZE,fp)) {
    buffer[strlen(buffer) -1] = '\0';
    Filter_insert (filter, buffer);
  }
  
  return filter;
}

void delete_Filter (Filter *filter) {
  Word *ptr;
  Word *ptr_next;
  
  for (ptr= filter->head; ptr; ptr = ptr->next) {
    ptr_next = ptr->next;
    free (ptr);
    ptr = ptr_next;
  }
  
  free (filter);
}

void print (Filter *filter) {
  Word *ptr;
  Word *ptr_next;
  
  for (ptr= filter->head; ptr; ptr = ptr->next) {
    printf("<%s>, <%s>\n", ptr->uncensored, ptr->censored);
  }
}
